import {addMenu, deleteMenu, getMenuById, treeMenu, updateMenuById} from '@/pages/system/menu/api';
import MenuEdit from '@/pages/system/menu/components/MenuEdit';
import {DeleteOutlined, PlusOutlined} from '@ant-design/icons';
import {ProCard} from '@ant-design/pro-components';
import {
  Alert,
  Badge,
  Button,
  Descriptions,
  GetProps,
  Input,
  message,
  Popconfirm,
  Space,
  Tag,
  Tree,
  TreeDataNode,
  TreeProps,
} from 'antd';
import React, {useEffect, useState} from 'react';

const mapTree = (item: any) => {
  if (!item) {
    return item;
  }
  const haveChildren = Array.isArray(item.children) && item.children.length > 0;
  // eslint-disable-next-line no-param-reassign
  item = {
    title: item.name,
    key: item.id,
    icon: item.icon,
    children: haveChildren ? item.children.map((i: any) => mapTree(i)) : [],
  };
  if (item.children.length <= 0) {
    delete item.children;
  }
  return item;
};

type SearchProps = GetProps<typeof Input.Search>;

const MenuTreeManager: React.FC = () => {
  const [menuInfo, setMenuInfo] = useState<API.IMenu>();
  const [treeData, setTreeData] = useState<TreeDataNode[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(false);
  const [searchName, setSearchName] = useState<string>('')

  const getMenuTree = async () => {
    try {
      const {data} = await treeMenu(searchName, 0);
      setTreeData(data.map((item: any) => mapTree(item)));
      // 默认展开第一级别的节点
      // const firstLevelKeys = data.map((item: any) => item.id);
      // setExpandedKeys(firstLevelKeys);
      // setSelectedKeys([firstLevelKeys[0]]); // 默认选中第一个
    } catch (e: any) {
      message.error(e);
    }
  };

  useEffect(() => {
    getMenuTree()
  }, []);

  const onExpand: TreeProps['onExpand'] = (expandedKeysValue) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const handleSelect = (id: string) => {
    getMenuById(id)
      .then((res) => {
        setMenuInfo(res.data);
      })
      .catch((e) => {
        message.error(e as string);
      });
  };

  const onSelect: TreeProps['onSelect'] = (selectedKeysValue, info) => {
    setSelectedKeys(selectedKeysValue);
    handleSelect(info.node.key as string);
  };

  const onSearch: SearchProps['onSearch'] = async (value) => {
    console.log(111)
    setSearchName(value)
    await getMenuTree();
  };

  return (
    <ProCard gutter={8} title="权限信息" style={{marginBlockStart: 8}}>
      <ProCard
        colSpan={8}
        bodyStyle={{maxHeight: '60vh', minHeight: '60vh', overflowY: 'auto'}} // 仅对内容区域生效
        bordered
      >
        <Space direction={'vertical'}>
          <Input.Search placeholder="请输入搜索菜单的名称" onSearch={onSearch}/>
          <Tree
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            onSelect={onSelect}
            selectedKeys={selectedKeys}
            treeData={treeData}
          />
        </Space>
      </ProCard>
      <ProCard
        colSpan={16}
        bordered
        title="菜单详情"
        extra={
          <Space>
            {menuInfo && (
              <MenuEdit
                isAdd={false}
                menu={menuInfo}
                key={`update`}
                onSubmit={async (values: API.IMenu) => {
                  console.log('修改数据:', values);
                  values.id = menuInfo?.id ?? 0;
                  values.version = menuInfo?.version ?? 0
                  const {data} = await updateMenuById(values);
                  if (data) {
                    setMenuInfo(data);
                    await getMenuTree()
                    message.success('修改成功');
                  }
                  return data;
                }}
              />
            )}
            <MenuEdit
              isAdd={true}
              onSubmit={async (values: API.IMenu) => {
                const {data} = await addMenu(values);
                if (data) {
                  message.success('添加成功');
                  await getMenuTree();
                }
                return data;
              }}
            />
            {menuInfo && (
              <MenuEdit
                isAdd={true}
                parentId={menuInfo.id}
                triggerButton={
                  <Button type="primary" icon={<PlusOutlined/>}>
                    添加子菜单
                  </Button>
                }
                onSubmit={async (values: API.IMenu) => {
                  const {data} = await addMenu(values);
                  if (data) {
                    message.success('添加成功');
                    await getMenuTree();
                  }
                  return data;
                }}
              />
            )}
            {menuInfo && (
              <Popconfirm
                title={`确认删除`}
                description={`确认删除【${menuInfo.name}】权限吗？`}
                okText="确认"
                cancelText="取消"
                onConfirm={async () => {
                  const {data} = await deleteMenu(menuInfo!.id!);
                  if (data) {
                    await getMenuTree();
                    message.success('删除成功');
                  }
                }}
              >
                <Button type="primary" icon={<DeleteOutlined/>} danger>
                  删除权限
                </Button>
              </Popconfirm>
            )}
          </Space>
        }
      >
        {menuInfo ? (
          <Descriptions bordered column={2} size={'small'}>
            <Descriptions.Item label="名称">{menuInfo?.name}</Descriptions.Item>
            <Descriptions.Item label="组件路径">{menuInfo?.component}</Descriptions.Item>
            <Descriptions.Item label="路由路径">{menuInfo?.path}</Descriptions.Item>
            <Descriptions.Item label="权限标识">{menuInfo?.perms}</Descriptions.Item>
            <Descriptions.Item label="路由名称">{menuInfo?.routeName}</Descriptions.Item>
            <Descriptions.Item label="菜单类型">
              {menuInfo?.menuType ? (
                menuInfo?.menuType === 'M' ? (
                  <Tag color="magenta">目录</Tag>
                ) : menuInfo?.menuType === 'C' ? (
                  <Tag color="gold">菜单</Tag>
                ) : (
                  <Tag color="purple">按钮</Tag>
                )
              ) : (
                '-'
              )}
            </Descriptions.Item>
            <Descriptions.Item label="父菜单ID">{menuInfo?.parentId}</Descriptions.Item>
            <Descriptions.Item label="排序号">{menuInfo?.orderNum}</Descriptions.Item>
            <Descriptions.Item label="是否缓存">
              {menuInfo?.isCache === 1 ? '是' : '否'}
            </Descriptions.Item>
            <Descriptions.Item label="是否外链">
              {menuInfo?.isFrame === 1 ? '是' : '否'}
            </Descriptions.Item>
            <Descriptions.Item label="是否可见">
              {menuInfo?.visible === '1' ? '是' : '否'}
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              {menuInfo?.status === '0' ? (
                <Badge color={'green'} text="正常"/>
              ) : (
                <Badge color="red" text="停用"/>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">{menuInfo?.createdAt}</Descriptions.Item>
            <Descriptions.Item label="创建人">{menuInfo?.createdBy}</Descriptions.Item>
            <Descriptions.Item label="备注">{menuInfo?.remark}</Descriptions.Item>
          </Descriptions>
        ) : (
          <Alert message={'请选择菜单'} type="info" showIcon/>
        )}
      </ProCard>
    </ProCard>
  );
};

export default MenuTreeManager;
